<template>
    <div class="Details">
        <van-swipe :autoplay="3000" indicator-color="skyblue">
            <van-swipe-item v-for="item in gallery" :key="item.id">
                <img v-lazy="item.img_url" width="100%" style="display: block" alt="">
            </van-swipe-item>
        </van-swipe>
        <Tips />
        <div class="goods_info">
            <h3>{{info.name}}</h3>
            <p>{{info.goods_brief}}</p>
            <section>{{info.retail_price | RMB}}</section>
        </div>
        <van-cell is-link @click="showPopup">展示弹出层</van-cell>
        <div class="good_canshu">
            <h3>商品参数</h3>
            <ul>
                <li v-for="(item,index) in attribute" :key="index">
                    <span>{{item.name}}</span>
                    <p>{{item.value}}</p>
                </li>
            </ul>
        </div>
        <div class="goods_desc" v-html="info.goods_desc"></div>
        <div class="title">
            <div class="line"></div>
            <h2>常见问题</h2>
        </div>
        <ul class="issue">
            <li v-for="item in issue" :key="item.id">
                <h3>{{item.question}}</h3>
                <p>{{item.answer}}</p>
            </li>
        </ul>
        <div class="title">
            <div class="line"></div>
            <h2>相关产品</h2>
        </div>
        <div class="mychanpin">
            <Chanpin :chanpinArr="goodsList" />
        </div>

        <van-popup v-model="popupShow" position="bottom" :style="{ height: '36.5%' }">
            <div class="sku">
                <div class="top">
                    <img :src="info.list_pic_url" alt="">
                    <div class="top_right">
                        <section>价格：{{info.retail_price | RMB}}</section>
                        <section>库存：{{info.goods_number}}</section>
                    </div>
                </div>
                <div class="down">
                    <section>数量：</section>
                    <div class="downd">
                        <van-stepper v-model="stepNum" min="1" :max="info.goods_number" />
                        <van-button type="warning" class="gofavbtn" size="small" @click="gofavbtn"
                            color="rgb(255,143,28)">跳转至我的收藏</van-button>
                    </div>
                </div>
                <van-icon name="cross" class="cross" @click="popupShow=false" />
            </div>
        </van-popup>
        <van-goods-action>
            <van-goods-action-icon :icon="isFav ? 'star' :'star-o'" :color="isFav?'rgb(255,143,28)':'inherit'"
                :text="isFav?'已收藏':'收藏'" @click="favBtn" />
            <van-goods-action-icon icon="cart-o" text="购物车" :badge="goodsCount" @click="gotoCart" />
            <van-goods-action-button type="danger" text="立即购买" />
            <van-goods-action-button type="warning" text="加入购物车" @click="addToCartFn" />
        </van-goods-action>
        <!-- <div style="height:50px"></div> -->
    </div>
</template>

<script>
    import Chanpin from '@/components/Chanpin.vue'
    import Tips from '@/components/Tips.vue'
    import {
        GoodsAboutApi,
        GoodsDetailApi,
        CartGoodsNumApi,
        CartAddApi
    } from "@/request/api"

    import Vue from 'vue'
    import {
        Toast
    } from 'vant';
    Vue.use(Toast);

    export default {
        data() {
            return {
                popupShow: false, // 默认关闭弹出层
                gallery: [], // 轮播图
                info: {}, // 商品信息
                attribute: [], // 产品参数
                issue: [], // 常见问题
                goodsList: [], // 相关产品的列表
                stepNum: 1, // 步进器的值
                goodsCount: 0, // 购物车数量
                productList: [],

                isFav: false, // 是否收藏

            }
        },
        async created() {
            // 请求商品数据
            await GoodsDetailApi({
                id: this.$route.params.id,
            }).then((res) => {
                // console.log(res);
                if (res.errno === 0) {
                    let {
                        gallery,
                        info,
                        attribute,
                        issue,
                        productList
                    } = res.data;
                    this.gallery = gallery;
                    this.info = info;
                    this.attribute = attribute;
                    this.issue = issue;
                    this.productList = productList;
                    // console.log(this.info);
                    // console.log(this.productList);
                }
            });

            // 获取购物车产品数量
            await CartGoodsNumApi().then(res => {
                if (res.errno === 0) {
                    let {
                        cartTotal
                    } = res.data;
                    this.goodsCount = cartTotal.goodsCount;
                }
            })

            // 请求相关产品
            await GoodsAboutApi({
                id: this.$route.params.id,
            }).then((res) => {
                // console.log(res);
                if (res.errno === 0) {
                    let {
                        goodsList
                    } = res.data;
                    this.goodsList = goodsList;
                }

            });

            // 判断商品是否已收藏
            let favArrInfoCreate = localStorage.getItem("favInfo");
            let favArrCreate = [];
            if (favArrInfoCreate) {
                // 如果localStorage有fav，则加入favArr
                favArrCreate = JSON.parse(favArrInfoCreate); // 反序列化
            }
            // 遍历数组，若商品已收藏，则改变isFav
            favArrCreate.forEach(element => {
                if (element.id == this.info.id && element.isfav == 1) {
                    this.isFav = true;
                }
            });

        },
        components: {
            Tips,
            Chanpin
        },
        methods: {
            // 跳转至收藏页面按钮
            gofavbtn() {
                this.$router.push("/favourite")
            },

            // 收藏方法
            changeFav(val) {
                let favArrInfo = localStorage.getItem("favInfo");
                let favArr = [];
                if (favArrInfo) {
                    // 如果localStorage有fav，则加入favArr
                    favArr = JSON.parse(favArrInfo); // 反序列化
                }
                // 设一个判断id是否存在数组的flag
                let favflag = false;
                // console.log(favArr);
                // 遍历数组
                favArr.forEach((element, index) => {
                    if (element.id == this.info.id) {
                        // 数组中存在该商品数据
                        if (val == 0) {
                            favArr.splice(index, 1);
                            favflag = true;
                        } else {
                            element.isfav = val;
                            element.pic_url = this.info.list_pic_url;
                            element.title = this.info.goods_brief;
                            element.price = this.info.retail_price;
                            element.brief = this.info.goods_brief;
                            element.product_id = this.productList[0].id;
                            favflag = true;
                        }
                    }
                });
                // 若遍历完后favflag仍为false，说明id不在数组中，将该商品是否收藏unshift进数组
                if (!favflag) {
                    favArr.unshift({
                        id: this.info.id,
                        isfav: val,
                        pic_url: this.info.list_pic_url,
                        title: this.info.name,
                        price: this.info.retail_price,
                        brief:this.info.goods_brief,
                        product_id: this.productList[0].id,
                    })
                };
                // console.log(favArr);
                // 将新数组存回localStorage
                localStorage.setItem("favInfo", JSON.stringify(favArr));
                // console.log(localStorage.getItem("favInfo"));
            },

            // 收藏按钮
            favBtn() {
                if (!this.isFav) {
                    // 添加收藏
                    this.changeFav(1);
                    this.isFav = !this.isFav;

                } else {
                    // 取消收藏
                    this.changeFav(0);
                    this.isFav = !this.isFav
                }
            },

            // 跳转到购物车
            gotoCart() {
                this.$router.push('/cart')
            },

            // 显示popup
            showPopup() {
                this.popupShow = true;
            },
            // 点击加入购物车
            addToCartFn() {
                // 判断popup到底有没有打开，如果没打开，就先打开popup
                if (this.popupShow) {
                    // 已经打开，等会该干啥就干啥
                    CartAddApi({
                        goodsId: this.$route.params.id,
                        productId: this.productList[0].id,
                        number: this.stepNum,
                    }).then((res) => {
                        // console.log(res);
                        if (res.errno === 0) {
                            this.goodsCount = res.data.cartTotal.goodsCount; // 重新渲染购物车数量
                            Toast.loading({
                                message: '添加成功！',
                                forbidClick: true,
                            })
                            setTimeout(() => {
                                this.popupShow = false; // 关闭遮罩层
                            }, 2000);


                        }
                    });
                } else {
                    this.popupShow = true;
                }
            }
        },
        // 监听路由的变化
        watch: {
            "$route.params.id": {
                handler(val, old) {
                    if (val !== old) {
                        this.$router.go(0); // 刷新当前页
                    }
                }
            }
        }
    }
</script>

<style lang="less" scoped>
    .Details {

        padding-bottom: 120px;

        .van-cell {
            margin-bottom: 20px;
        }

        .goods_info {
            background: #fff;
            text-align: center;
            line-height: 40px;
            padding: 20px 0;
            border-bottom: 1px solid #ccc;

            h3 {
                font-size: 20px;
            }

            p {
                margin: 5px 0;
            }

            section {
                color: darkred;
            }
        }

        .good_canshu {
            font-size: 18px;
            background: #fff;
            padding: 10px;

            ul {
                margin-top: 10px;
                font-size: 14px;

                li {
                    border-radius: 6px;
                    background: #efefef;
                    margin-bottom: 10px;
                    display: flex;
                    height: 30px;
                    justify-content: space-between;
                    align-items: center;

                    span {
                        width: 20%;
                        text-align: right;
                        color: #999;
                        margin-right: 10px;
                    }

                    p {
                        flex: 1;
                        text-overflow: ellipsis;
                        overflow: hidden;
                        white-space: nowrap;
                    }
                }
            }
        }

        /* less和sass - 预编译语言 - deep深度修改样式 */
        /deep/.goods_desc {
            width: 100%;

            p {
                margin: 0;

                img {
                    display: block;
                    width: 100%;
                }
            }
        }

        .title {
            height: 40px;
            background: #fff;
            position: relative;

            .line {
                width: 50%;
                background: #ccc;
                position: absolute;
                height: 2px;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                margin: auto;
            }

            h2 {
                width: 30%;
                background: #fff;
                position: absolute;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                font-size: 16px;
                line-height: 40px;
                margin: auto;
                text-align: center;
            }
        }

        .issue {
            background: #fff;
            padding: 10px 20px;

            li {
                h3 {
                    font-size: 14px;
                    position: relative;

                    &::before {
                        content: "";
                        width: 4px;
                        height: 4px;
                        border-radius: 50%;
                        background: darkred;
                        position: absolute;
                        left: -10px;
                        top: 50%;
                        margin-top: -2px;
                    }
                }

                p {
                    font-size: 12px;
                    color: #999;
                }
            }
        }

        .mychanpin {
            background: #fff;
        }

        .van-goods-action {
            z-index: 3000;
        }

        .sku {
            width: 100%;
            min-height: 30vh;
            background: #fff;
            position: absolute;
            left: 0;
            bottom: 50px;
            padding: 10px;
            box-sizing: border-box;

            .top {
                display: flex;
                justify-content: space-between;

                img {
                    width: 100px;
                    margin-right: 10px;
                }

                .top_right {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;
                }
            }

            .down {
                section {
                    font-size: 20px;
                    margin-top: 20px;
                    margin-bottom: 20px;
                }

                .downd {

                    .van-stepper {
                        font-size: 0;
                        -webkit-user-select: none;
                        user-select: none;
                        float: left;

                    }

                    .gofavbtn {
                        float: right;
                        height: 28px;
                        border-radius: 20px;
                    }
                }

            }

            .cross {
                position: absolute;
                right: 10px;
                top: 10px;
                font-size: 20px;
            }

        }
    }
</style>